#include "serveur.h"
int creationSocket_Serveur(const char * port) {
  struct addrinfo hints;
  struct addrinfo * result, * rp;
  int res, bon, sock_err, s;
    
  memset(&hints, 0, sizeof(struct addrinfo));
  hints.ai_family = AF_INET;
  hints.ai_socktype = SOCK_STREAM;
  hints.ai_flags = AI_PASSIVE;
  
  res = getaddrinfo(NULL, port, &hints, &result);
  if(res != 0)
    {
      fprintf(stderr, "[svr]! Erreur getaddinfo : %s.\n",gai_strerror(res));
      exit(1);
    }
  
  bon = 0;
  for( rp = result; rp != NULL; rp = rp->ai_next){
    s = socket (rp->ai_family, rp->ai_socktype, rp->ai_protocol);
    if( s == -1) 
      {
	fprintf(stderr, "[svr]! Erreur socket : Création de la socket impossible.\n");
	continue;
      }
    res = bind(s , rp->ai_addr, rp->ai_addrlen);
    if (res == 0)
      {
	bon = 1;
	break;
      }
    fprintf(stderr, "[svr]! Erreur bins : Impossible de réserver l'adresse.\n");
    close(s);
  }
  freeaddrinfo(result);
  if (bon == 0)
    {
      fprintf(stderr, "[svr]! Erreur : Impossible d'obtenir une adresse.\n");
      exit(1);
    }
  
  sock_err = listen(s, 5);
  
  if(sock_err == -1)
    {
      perror("[svr]! Erreur listen.");
      close(s);
      exit(1);
    }
  
  return s;
}

int attenteConnexion_Serveur(int socket)
{
  int t, res;
  struct sockaddr_storage taddr;
  socklen_t taddrlen = sizeof(taddr);
  char hname[NI_MAXHOST], sname [NI_MAXSERV];

  t = accept(socket, (struct sockaddr *)&taddr, &taddrlen);
  printf("\n[svr]> Connexion en cours...\n");
  res = getnameinfo((struct sockaddr *)&taddr, taddrlen,
		    hname, NI_MAXHOST,
		    sname, NI_MAXSERV,
		    NI_NUMERICSERV);
  if(res !=0) {
    fprintf(stderr, "[svr]! Erreur getnameinfo : %s.\n", gai_strerror(res));
    exit(1);
  }
  
  printf ("[svr]> Nouveau client connecté sur la socket %d depuis %s sur le port %s.\n", t , hname, sname);

  return t;
}

